package org.lemon.transport.coap.server.config;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.lemon.transport.context.config.ssl.KeystoreSslCredentials;
import org.lemon.transport.context.config.ssl.PemSslCredentials;
import org.lemon.transport.context.config.ssl.SslCredentials;
import org.lemon.transport.context.config.ssl.SslCredentialsType;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;


@Data
@Slf4j
@Configuration
@ConfigurationProperties(prefix = "transport.coap.dtls.credentials")
public class SslCredentialsConfig {

    @Value("${transport.coap.dtls.enabled}")
    private boolean enabled;

    private SslCredentialsType type;
    private PemSslCredentials pem;
    private KeystoreSslCredentials keystore;

    private SslCredentials credentials;

    private final String name = "Coap SSL Credentials";
    private final boolean trustsOnly = false;

    @PostConstruct
    public void init() {

        if (this.enabled) {
            log.info("{}: Initializing SSL credentials.", name);
            if (SslCredentialsType.PEM.equals(type)) {
                this.credentials = this.pem;
            } else if (SslCredentialsType.KEYSTORE.equals(type)) {
                this.credentials = this.keystore;
            } else {
                throw new RuntimeException(name + ": Invalid SSL credentials configuration. None of the PEM or KEYSTORE configurations can be used!");
            }
            try {
                this.credentials.init(this.trustsOnly);
            } catch (Exception e) {
                throw new RuntimeException(name + ": Failed to init SSL credentials configuration.", e);
            }
        } else {
            log.info("{}: Skipping initialization of disabled SSL credentials.", name);
        }
    }
}
